package com.zz.chenko.sys.web;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.zz.chenko.common.base.BaseController;
import com.zz.chenko.common.entity.Message;
import com.zz.chenko.common.entity.TreeObject;
import com.zz.chenko.common.utils.*;
import com.zz.chenko.sys.dto.UserDto;
import com.zz.chenko.sys.entity.*;
import com.zz.chenko.sys.service.*;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 登录Controller
 * @author zhong
 * @since 2016年11月9日
 */

@Controller
public class LoginController extends BaseController {

    @Autowired
    private UserService userService;
    @Autowired
    private RolePermissionService rolePermissionService;
    @Autowired
    private UserRoleService userRoleService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private PermissionService permissionService;
    @Autowired
    private RoleMenuService roleMenuService;
    @Autowired
    private MenuService menuService;

    // @PathVariable String loginName, @PathVariable String password,

    /**
     * 跳转登录页
     * 
     * @return
     */
    @RequestMapping("/sys/login")
    public ModelAndView login() {
        User user = UserUtil.getUser();
        if (user.getId() != null) {
            return new ModelAndView("index");
        }
        return new ModelAndView("login");
    }

    /**
     * 判断登录
     * 
     * @return
     */
    @RequestMapping(value = { "", "index" })
    public ModelAndView index(HttpServletRequest request) {
        User user = UserUtil.getUser();
        if (user.getId() != null) {
            logger.info("用户[{}]通过cookie登录成功", user.getLoginName());
            ModelAndView modelAndView = new ModelAndView("index");
            setUserInfoToCache(user.getId());
            // 当验证都通过后，把用户信息放在session里
            Session session = SecurityUtils.getSubject().getSession();
            session.setAttribute("user", user);
            session.setAttribute("userId", user.getId());
            session.setAttribute("menuStr", MenuUtil.getMenu(request));
            return modelAndView;
        }
        return new ModelAndView("login");
    }

    /**
     * 用户登陆
     */
    @RequestMapping(value = "/sys/login/access", method = RequestMethod.GET)
    public ModelAndView accessGet(HttpServletRequest request) {
        return new ModelAndView("redirect:/index");
    }

    /**
     * 用户登陆
     * 
     * @param userDto
     * @param remember 记住我
     * @return
     */
    @RequestMapping(value = "/sys/login/access", method = RequestMethod.POST)
    public ModelAndView accessPost(UserDto userDto, boolean remember, HttpServletRequest request) {
        UsernamePasswordToken token = new UsernamePasswordToken(userDto.getLoginName(), userDto.getLoginPassword());
        Subject currentUser = SecurityUtils.getSubject();
        token.setRememberMe(remember);
        ModelAndView modelAndView = null;
        try {
            currentUser.login(token);
            logger.info("用户[{}]通过密码登录成功", userDto.getLoginName());
            Session session = SecurityUtils.getSubject().getSession();
            User user = (User) session.getAttribute("user");
            setUserInfoToCache(user.getId());
            session.setAttribute("menuStr", MenuUtil.getMenu(request));
            modelAndView = new ModelAndView("index");
            return modelAndView;
        } catch (IncorrectCredentialsException ice) {
            token.clear();
            modelAndView = new ModelAndView("login");
            modelAndView.addObject("message", new Message("用户名或密码错误，请重新确认！", "danger"));
            logger.error(ice.getMessage());
            return modelAndView;
        } catch (Exception e) {
            token.clear();
            modelAndView = new ModelAndView("login");
            modelAndView.addObject("message", new Message(e.getMessage(), "danger"));
            modelAndView.addObject("userDto", userDto);
            logger.error(e.getMessage());
            return modelAndView;
        }
    }

    /**
     * 用户退出
     * 
     * @return
     */
    @RequestMapping(value = "/sys/logout")
    public ModelAndView logout() {
        User user = UserUtil.getUser();
        // 使用权限管理工具进行用户的退出，注销登录
        SecurityUtils.getSubject().logout();

        logger.info("用户[{}]成功退出", user.getLoginName());
        return new ModelAndView("login");
    }

    /**
     * 将当前用户的信息添加到缓存中
     */
    private void setUserInfoToCache(Long userId) {
        // 取得当前用户所有角色
        Map<String, Object> map = new HashMap<>();
        map.put("USER_ID", userId);
        List<UserRole> userRoleList = userRoleService.selectByMap(map);
        List roleIds = CollectionUtil.extractToList(userRoleList, "roleId");
        List<Role> roleList = roleService.selectBatchIds(roleIds);
        // 将角色加入到缓存中
        CacheUtil.put("role", "roleList", roleList);

        // 取得当前用户所有菜单
        EntityWrapper<RoleMenu> rmWrapper = new EntityWrapper<>();
        rmWrapper.in("ROLE_ID", roleIds);
        List<RoleMenu> roleMenuList = roleMenuService.selectList(rmWrapper);
        List<Long> menuIds = CollectionUtil.extractToList(roleMenuList, "menuId");
        EntityWrapper<Menu> mWrapper = new EntityWrapper<Menu>();
        mWrapper.in("ID", menuIds).orderBy("PARENT_ID, SORT");
        List<Menu> menuList = menuService.selectList(mWrapper);
        List<TreeObject> list = new ArrayList<TreeObject>();
        for (Menu menu : menuList) {
            TreeObject ts = new TreeObject();
            ts.setItem(menu);
            list.add(ts);
        }
        TreeUtil treeUtil = new TreeUtil();
        List<TreeObject> ns = treeUtil.getChildTreeObjects(list, 0L);

        // 将menu添加到缓存中
        CacheUtil.put("menu", "menuList", menuList);
        CacheUtil.put("menu", "menuTree", ns);

        // 取得当前用户所有权限
        EntityWrapper<RolePermission> rpWrapper = new EntityWrapper<RolePermission>();
        rpWrapper.in("ROLE_ID", roleIds);
        List<RolePermission> rpList = rolePermissionService.selectList(rpWrapper);
        List<Long> permissionIds = CollectionUtil.extractToList(rpList, "permissionId");
        List<Permission> permissionList = permissionService.selectBatchIds(permissionIds);
        // 将权限加入到缓存中
        CacheUtil.put("permission", "permissionList", permissionList);
    }
}
